#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define SIZE 256
#define MAX_ARGC 16

char *argv[MAX_ARGC];

void my_cd()
{
    pid_t pid;
    pid = fork();
    if(pid == 0) {
      int error = chdir(argv[1]);
      if(error < 0)
        perror("cd");
    }
    wait(NULL);
}

void my_pwd()
{
    pid_t pid;
    pid = fork();
    if(pid == 0) {
      char *p=getcwd(NULL, 0);
      if(p==NULL)
        perror("execvp");
      printf("%s\n", p);
    }
    wait(NULL);
}

void my_exit()
{
    exit(0);
}

void mysys(char *command) {
    char *line = (char *)malloc(sizeof(command));
    strcpy(line, command);

    int argc = 0;
    for(int i = 0; i < MAX_ARGC; i++)
    	argv[i] = NULL;
    char *word;
    char *delim = " \n";
    word = strtok(line, delim);
    while(word != NULL) {
      argv[argc] = word;
      word = strtok(NULL, delim);
      argc++;
    }

    if(strcmp(argv[0], "cd")==0)
    {
            my_cd();
            return;
    }
    if(strcmp(argv[0], "pwd")==0)
    {
            my_pwd();
            return;
    }
    if(strcmp(argv[0], "exit")==0)
    {
            my_exit();
            return;
    }


    pid_t pid;
    pid = fork();
    if(pid == 0) {
      int error = execvp(argv[0], argv);
      if(error < 0)
        perror("execvp");
    }
    wait(NULL);
}



int main() {
	char command[SIZE];
	int longth;
	while(1)
	{
		write(1, ">", sizeof(">"));
		longth=read(0, command, sizeof(command));
		command[longth] = 0;
		mysys(command);
	}
}

